package com.hpin.mlxteacher.ui;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.MyAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.SchoolClassReq;
import com.hpin.mlxteacher.bean.VerRes;
import com.hpin.mlxteacher.db.DatabaseManager;
import com.hpin.mlxteacher.fragment.BabyTreeFragment;
import com.hpin.mlxteacher.fragment.ChatFragment;
import com.hpin.mlxteacher.fragment.ChildFragment;
import com.hpin.mlxteacher.fragment.MyFragement;
import com.hpin.mlxteacher.message.ChoosePhotoActivity;
import com.hpin.mlxteacher.tree.ReleaseActivity;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.LogUtil;
import com.hpin.mlxteacher.widget.ActionSheetDialog;
import com.umeng.update.UmengUpdateAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;


//import com.umeng.analytics.MobclickAgent;

/**
 * Created by Administrator on 2015/7/14.
 */
public class HomeActivity extends BaseActivity {

//    private FrameLayout fl_base;
    /**
     * fragment 管理者
     */
    private FragmentManager manager;
    //    private NewsFragment newsFragment;
    private ChildFragment childFragment;
    private BabyTreeFragment babyTreeFragment;
    private MyFragement myFragement;
    private TextView tv_message;
    private TextView tv_child;
    private TextView tv_baby_tree;
    private TextView tv_my;
    private ImageView iv_message;
    private ImageView iv_child;
    private ImageView iv_photo;
    private ImageView iv_baby_tree;
    private ImageView iv_my;
    /*拍照的文件保存的位置*/
    private File currentFile;
    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 1031;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 1032;

    private ViewGroup ic_home_bottom;
    private Intent mIntent;

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationListenner myListener = new MyLocationListenner();
    // 定位相关
    private LocationClient mLocClient;
    //是否是第一次定位
    private boolean isFirstLoc = true;
    private TextView tv_msg_count;
    private ChatFragment chatFragment;
    //    private Token token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_home);

        //开启服务,登录mqtt
        mApplication.loginMqtt();

        initWidget();

        initFragment();

//        友盟检查更新
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);
//        UpdateConfig.setDebug(true);//debug模式,发布时删除

        //获取配置版本信息
        getVersionInfo();

        //如果没有获取过班级信息则 获取班级信息 并默认选择第一个
        if (CommonUtils.isNull(sp.getString(Constant.classId, "")))
            myClasses();

        EventBus.getDefault().register(this);
    }

    private void initWidget() {
//        fl_base = (FrameLayout) findViewById(R.id.fl_base);

        RelativeLayout rl_message = (RelativeLayout) findViewById(R.id.rl_message);
        RelativeLayout rl_child = (RelativeLayout) findViewById(R.id.rl_child);
        RelativeLayout rl_baby_tree = (RelativeLayout) findViewById(R.id.rl_baby_tree);
        RelativeLayout rl_my = (RelativeLayout) findViewById(R.id.rl_my);

        iv_message = (ImageView) findViewById(R.id.iv_message);
        iv_child = (ImageView) findViewById(R.id.iv_child);
        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        iv_baby_tree = (ImageView) findViewById(R.id.iv_baby_tree);
        iv_my = (ImageView) findViewById(R.id.iv_my);

        ic_home_bottom = (ViewGroup) findViewById(R.id.ic_home_bottom);
        tv_msg_count = (TextView) findViewById(R.id.tv_msg_count);

        tv_message = (TextView) findViewById(R.id.tv_message);
        tv_child = (TextView) findViewById(R.id.tv_child);
        tv_baby_tree = (TextView) findViewById(R.id.tv_baby_tree);
        tv_my = (TextView) findViewById(R.id.tv_my);

        rl_message.setOnClickListener(this);
        rl_child.setOnClickListener(this);
        rl_baby_tree.setOnClickListener(this);
        rl_my.setOnClickListener(this);
        iv_photo.setOnClickListener(this);

//        getMsgCount();

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);

        // 获取地图控件引用
        mBaiduMap = mMapView.getMap();

        getMyLocation();

    }

    /**
     * 隐藏底部按钮
     */
    public void hitButtom() {
        ic_home_bottom.setVisibility(View.GONE);
    }

    /**
     * 显示底部按钮
     */
    public void showButtom() {
        ic_home_bottom.setVisibility(View.VISIBLE);
    }

    private void initFragment() {

        manager = getFragmentManager();

        iv_message.setSelected(true);
        tv_message.setTextColor(getResources().getColor(R.color.red));

        chooseFragment(0);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.rl_message:

                //把所有的图标都变灰
                setSelectFalse();

                //消息
                chooseFragment(0);

                //改变字体颜色和图片
                iv_message.setSelected(true);
                tv_message.setTextColor(getResources().getColor(R.color.red));
                break;

            case R.id.rl_child:

                //把所有的图标都变灰
                setSelectFalse();
                //孩子
                chooseFragment(1);

                iv_child.setSelected(true);
                tv_child.setTextColor(getResources().getColor(R.color.red));
                break;
            case R.id.rl_baby_tree:

                //把所有的图标都变灰
                setSelectFalse();

                //宝宝树
                chooseFragment(3);

                iv_baby_tree.setSelected(true);
                tv_baby_tree.setTextColor(getResources().getColor(R.color.red));
                break;
            case R.id.rl_my:

                //把所有的图标都变灰
                setSelectFalse();
                //我的
                chooseFragment(4);

                iv_my.setSelected(true);
                tv_my.setTextColor(getResources().getColor(R.color.red));

                break;
            case R.id.iv_photo:

                showChoose();

                break;

        }
    }

    /**
     * 获取配置版本信息
     */
    private void getVersionInfo() {

        final JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("ver", getAppVersionName(this));
        j.put("build", sp.getString(Constant.build, ""));

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT + Constant.VERSION,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        LogUtil.e("tag", "版本信息==" + response);

                        try {

                            VerRes verRes = JSONObject.parseObject(response, VerRes.class);

                            if (verRes.code == 1011) {//1011 需要更新本地配置文件

                                SharedPreferences.Editor edit = sp.edit();
                                //保存服务器的配置版本
                                edit.putString(Constant.build, verRes.build);
                                edit.apply();

                                if (verRes.data != null) {

                                    //保存配置信息到本地
                                    CommonUtils.fileSave(Constant.VERDATA, verRes);

                                }

                            } else if (verRes.code == 1008) {
                                //提示版本更新
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtil.e("tag", "版本信息==失败");
            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", j.toJSONString());

//                LogUtil.e("TAG", "请求的json===>>>>" + params);

                return param;
            }

        };
        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
//            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            LogUtil.e("tag", e);
        }
        return versionName;
    }

    /**
     * /**
     * 获取我的班级
     */
    private void myClasses() {

        final JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT + Constant.MYCLASSES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            //如果没有选择过 则默认选择第一个班级
                            SchoolClassReq result = JSONObject.parseObject(response, SchoolClassReq.class);
                            SharedPreferences.Editor edit = sp.edit();

                            if (result.data.size() < 1) {
//                                showToast("未查询到班级信息");
                                return;
                            }

                            edit.putString(Constant.classId, result.data.get(0).id);
                            edit.putString(Constant.className, result.data.get(0).nickName);
                            edit.apply();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", j.toJSONString());

                return param;
            }

        };

        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    /**
     * 选择对应的fragment
     *
     * @param index 对应的fragment的角标
     */
    private void chooseFragment(int index) {

        FragmentTransaction transaction = null;
        if (manager != null) {
            transaction = manager.beginTransaction();
        }
        // 先移除掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
//        removeFragments(transaction);

        if (transaction == null)
            return;

        switch (index) {

            case 0:
                //消息

                if (chatFragment == null)
                    chatFragment = new ChatFragment();

                transaction.replace(R.id.fl_base, chatFragment, Constant.NEWS);

                break;

            case 1:

                if (childFragment == null)
                    childFragment = new ChildFragment();

                transaction.replace(R.id.fl_base, childFragment, Constant.CHILD);

                break;

//            case 2:
//
//                break;
            case 3:
                if (babyTreeFragment == null)
                    babyTreeFragment = new BabyTreeFragment();

                transaction.replace(R.id.fl_base, babyTreeFragment, Constant.BABYTREE);

                break;
            case 4:

                if (myFragement == null)
                    myFragement = new MyFragement();

                transaction.replace(R.id.fl_base, myFragement, Constant.MY);

                break;

        }

        if (transaction != null) {
//            transaction.commit();
            transaction.commitAllowingStateLoss();
        }

    }

    //    /**
//     * 移除fragment
//     *
//     * @param transaction
//     */
//    private void removeFragments(FragmentTransaction transaction) {
//        if (transaction == null)
//            return;
//
//        if (newsFragment != null) {
//            transaction.remove(newsFragment);
//        }
//        if (childFragment != null) {
//            transaction.remove(childFragment);
//        }
//        if (babyTreeFragment != null) {
//            transaction.remove(babyTreeFragment);
//        }
//        if (myFragement != null) {
//            transaction.remove(myFragement);
//        }
//
//    }


    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + "/mlxCache";
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case TAKE_PHOTO_CODE: //拍照
//                if (data == null)
//                    return;
                if (currentFile != null && currentFile.exists()) {

                    mIntent = new Intent(this, ReleaseActivity.class);
                    mIntent.putExtra("take_photo", currentFile.getPath());
                    currentFile = null;
                    startActivity(mIntent);

                }

                break;

            case PHOTO_ALBUM_CODE://相册选择

                if (data == null) {
                    MyAdapter.mSelectedImage.clear();
                    return;
                }

                //获取到传过来的图片的集合
                ArrayList<String> tempPhotos = data.getStringArrayListExtra("selectedPhotos");
                mIntent = new Intent(this, ReleaseActivity.class);
                mIntent.putStringArrayListExtra("choose_photo", tempPhotos);
                startActivity(mIntent);

                break;

        }

    }

    /**
     * 把所有的图标都变灰
     * 字体还原
     */
    private void setSelectFalse() {

        iv_message.setSelected(false);
        iv_child.setSelected(false);
        iv_photo.setSelected(false);
        iv_baby_tree.setSelected(false);
        iv_my.setSelected(false);

        tv_message.setTextColor(getResources().getColor(R.color.text_color));
        tv_child.setTextColor(getResources().getColor(R.color.text_color));
        tv_baby_tree.setTextColor(getResources().getColor(R.color.text_color));
        tv_my.setTextColor(getResources().getColor(R.color.text_color));

    }

    private long mPressedTime = 0;

    @Override
    public void onBackPressed() {

        long mNowTime = System.currentTimeMillis();//获取第一次按键时间

        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差

            showToast("再按一次退出程序");

            mPressedTime = mNowTime;

        } else {//退出程序

            //退出app
            finish();
            mApplication.exit();
        }
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            SharedPreferences.Editor edit = sp.edit();
            edit.putString(Constant.CITYNAME, location.getCity());
            edit.apply();

            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            mApplication.myLatitude = location.getLatitude();
            mApplication.myLongitude = location.getLongitude();

            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
//                //如果未绑定设备则定位到我的位置,否则定位到手表的位置
//                if (TextUtils.isEmpty(currentWatchId)) {

                try {
                    LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                    if (mBaiduMap != null)
                        mBaiduMap.animateMapStatus(u);
                } catch (Exception e) {
                    e.printStackTrace();

                }

//                }
            }

        }

    }

    /**
     * 获取到我的当前位置
     */
    private void getMyLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_center_point_my);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);//需要返回地址,即 哪个市
        option.setAddrType("all"); //类型
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(100000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }


    /**
     * 更新小红点
     *
     * @param msb
     */
    public void onEventMainThread(String msb) {

        if (Constant.UPDATE_RED_COUNT.equals(msb))
            setRedCount();

    }

    // 设置红点个数
    public void setRedCount() {

        int sum = DatabaseManager.getInstance().queryAllUnReadCount(this, sp.getString(Constant.phoneNum, ""));

        if (sum == -100)
            return;

        if (sum > 99) sum = 99;
        tv_msg_count.setText(sum + "");
        tv_msg_count.setVisibility(sum > 0 ? View.VISIBLE : View.INVISIBLE);

    }


    @Override
    public void onDestroy() {

        if (mMapView != null)
            mMapView.onDestroy();

        EventBus.getDefault().unregister(this);

        super.onDestroy();

    }

    public void onResume() {
        super.onResume();

        // 在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onResume();

        setRedCount();

    }

    public void onPause() {
        super.onPause();

        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onPause();

    }

}
